package dao.impl;

import java.util.Iterator;
import java.util.List;

import libs.Global;
import libs.Utils;
import models.Users;
import dao.UserDao;

public class UserDaoImpl implements UserDao {
	@Override
    public boolean checkExistByUsername(String username) {
            return true;
    }

    @Override
    public void insert(Users user) {
            Global.entityManager.getTransaction().begin();
            Global.entityManager.persist(user);
            Global.entityManager.getTransaction().commit();
    }

    @Override
    public Users selectByUsernameAndPassword(String username, String password) {
            Iterator<Users> iter = Global.entityManager
                            .createQuery("SELECT usr FROM Users AS usr WHERE usr.username = :username AND usr.password = :password",
                                            Users.class).setParameter("username", username).setParameter("password", Utils.hashSHA1(password))
                            .getResultList().iterator();
            if (iter.hasNext()) {
                    return iter.next();
            }
            return null;
    }

    @Override
    public int count(Users user) {
            return Global.entityManager.createQuery("SELECT usr FROM User AS usr", Integer.class).getSingleResult();
    }

    public List<Users> selectAll() {
            return Global.entityManager.createQuery("SELECT usr FROM User AS usr", Users.class).getResultList();
    }
}
